package cn.zyjblogs.starter.minio.service;

import cn.zyjblogs.starter.common.entity.response.HttpCode;
import cn.zyjblogs.starter.minio.config.MinioProperties;
import cn.zyjblogs.starter.minio.exception.MinioBusinessException;
import com.alibaba.excel.util.StringUtils;
import com.google.common.collect.Lists;
import io.jsonwebtoken.lang.Assert;
import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

public class MinioService {
    private static final Logger log = LoggerFactory.getLogger(MinioService.class);
    public static final long MAX_PART_SIZE = 5368709120L;

    private final MinioClient minioClient;
    private final MinioProperties minioProperties;

    public MinioService(MinioClient minioClient, MinioProperties minioProperties) {
        this.minioClient = minioClient;
        this.minioProperties = minioProperties;
    }


    /**
     * 桶是否存在
     *
     * @param bucketName 桶名
     * @return java.lang.Boolean
     * @author daiweixing
     * @date 2021/11/3 10:35
     */
    public boolean bucketExists(String bucketName) {
        try {
            return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 创建桶
     *
     * @param bucketName 桶名
     * @return void
     * @date 2021/11/3 10:35
     */
    public void makeBucket(String bucketName) {
        try {
            if (bucketExists(bucketName)) {
                return;
            }
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        } catch (MinioBusinessException e) {
            log.error("Failed to make bucket, because the bucket exists", e);
            if (e.getMessage() != null) {
                throw e;
            }
        } catch (Exception e) {
            log.error("Failed to make bucket", e);
            throw new MinioBusinessException(HttpCode.INTERNAL_SERVER_ERROR, "Failed to make bucket");
        }
    }

    /**
     * 删除桶
     *
     * @param bucketName 桶名
     * @return void
     * @date 2021/11/3 10:35
     */
    public void removeBucket(String bucketName) {
        try {
            if (!bucketExists(bucketName)) {
                return;
            }
            minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
        } catch (MinioBusinessException e) {
            log.error("Failed to remove bucket, because the bucket not found", e);
            if (e.getMessage() != null) {
                throw e;
            }
        } catch (Exception e) {
            log.error("Failed to remove bucket", e);
            throw new MinioBusinessException(HttpCode.INTERNAL_SERVER_ERROR, "Failed to remove bucket");
        }
    }

    /**
     * 通过流上传文件
     *
     * @param bucketName  桶名
     * @param objectName  对象名称
     * @param stream      文件输入流
     * @param contentType Content-Type
     * @return void
     * @date 2021/11/3 10:35
     */
    public void putObject(String bucketName, String objectName, InputStream stream, String contentType) {
        try {
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .stream(stream, stream.available(), MAX_PART_SIZE)
                    .contentType(contentType)
                    .build());
            stream.close();
        } catch (Exception e) {
            log.error("Failed to put object through stream", e);
            throw new MinioBusinessException(HttpCode.INTERNAL_SERVER_ERROR, "Failed to put object");
        }
    }

    /**
     * 通过流上传文件
     *
     * @param objectName  对象名称
     * @param stream      文件输入流
     * @param contentType Content-Type
     * @return void
     * @date 2021/11/3 10:35
     */
    public void putObject(String objectName, InputStream stream, String contentType) {
        try {
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .object(objectName)
                    .stream(stream, stream.available(), MAX_PART_SIZE)
                    .contentType(contentType)
                    .build());
            stream.close();
        } catch (Exception e) {
            log.error("Failed to put object through stream", e);
            throw new MinioBusinessException(HttpCode.INTERNAL_SERVER_ERROR, "Failed to put object");
        }
    }

    /**
     * 上传本地文件
     *
     * @param bucketName  桶名
     * @param objectName  对象名称
     * @param fileName    文件路径
     * @param contentType Content-Type
     * @return void
     * @date 2021/11/3 10:35
     */
    public void uploadObject(String bucketName, String objectName, String fileName, String contentType) {
        try {
            if (StringUtils.isEmpty(contentType)) {
                minioClient.uploadObject(UploadObjectArgs.builder().bucket(bucketName).object(objectName).filename(fileName).build());
            } else {
                minioClient.uploadObject(UploadObjectArgs.builder().bucket(bucketName).object(objectName).filename(fileName).contentType(contentType).build());
            }
        } catch (Exception e) {
            log.error("Failed to upload object through fileName", e);
            throw new MinioBusinessException(HttpCode.INTERNAL_SERVER_ERROR, "Failed to upload object");
        }
    }

    /**
     * 上传本地文件
     *
     * @param objectName  对象名称
     * @param fileName    文件路径
     * @param contentType Content-Type
     * @return void
     * @date 2021/11/3 10:35
     */
    public void uploadObject(String objectName, String fileName, String contentType) {
        try {
            if (StringUtils.isEmpty(contentType)) {
                minioClient.uploadObject(UploadObjectArgs.builder().bucket(minioProperties.getBucketName()).object(objectName).filename(fileName).build());
            } else {
                minioClient.uploadObject(UploadObjectArgs.builder().bucket(minioProperties.getBucketName()).object(objectName).filename(fileName).contentType(contentType).build());
            }
        } catch (Exception e) {
            log.error("Failed to upload object through fileName", e);
            throw new MinioBusinessException(HttpCode.INTERNAL_SERVER_ERROR, "Failed to upload object");
        }
    }

    /**
     * 通过MultipartFile，上传文件
     *
     * @param bucketName  桶名
     * @param objectName  对象名称
     * @param file        MultipartFile文件
     * @param contentType Content-Type
     * @return void
     * @date 2021/11/3 10:35
     */
    public void putObject(String bucketName, String objectName, MultipartFile file, String contentType) {
        try {
            this.putObject(bucketName, objectName, file.getInputStream(), contentType);
        } catch (Exception e) {
            log.error("Failed to put object through multipartFile", e);
            throw new MinioBusinessException(HttpCode.INTERNAL_SERVER_ERROR, "Failed to put object");
        }
    }

    /**
     * 通过MultipartFile，上传文件
     *
     * @param objectName  对象名称
     * @param file        MultipartFile文件
     * @param contentType Content-Type
     * @return void
     * @date 2021/11/3 10:35
     */
    public void putObject(String objectName, MultipartFile file, String contentType) {
        try {
            this.putObject(minioProperties.getBucketName(), objectName, file.getInputStream(), contentType);
        } catch (Exception e) {
            log.error("Failed to put object through multipartFile", e);
            throw new MinioBusinessException(HttpCode.INTERNAL_SERVER_ERROR, "Failed to put object");
        }
    }

    /**
     * 删除文件
     *
     * @param bucketName 桶名
     * @param objectName 对象名称
     * @return void
     * @date 2021/11/3 10:35
     */
    public void removeObject(String bucketName, String objectName) {
        try {
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
        } catch (Exception e) {
            log.error("Failed to remove object", e);
            throw new MinioBusinessException(HttpCode.INTERNAL_SERVER_ERROR, "Failed to remove object");
        }
    }

    /**
     * 删除文件
     *
     * @param objectName 对象名称
     * @return void
     * @date 2021/11/3 10:35
     */
    public void removeObject(String objectName) {
        try {
            minioClient.removeObject(RemoveObjectArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .object(objectName)
                    .build());
        } catch (Exception e) {
            log.error("Failed to remove object", e);
            throw new MinioBusinessException(HttpCode.INTERNAL_SERVER_ERROR, "Failed to remove object");
        }
    }

    /**
     * 批量删除文件
     *
     * @param bucketName     桶名
     * @param objectNameList 对象名称集合
     * @return void
     * @date 2021/11/3 10:35
     */
    public void batchRemoveObject(String bucketName, List<String> objectNameList) {
        minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName).objects(objectNameList.stream().map(DeleteObject::new).collect(Collectors.toList())).build());
    }

    /**
     * 批量删除文件
     *
     * @param objectNameList 对象名称集合
     * @return void
     * @date 2021/11/3 10:35
     */
    public void batchRemoveObject(List<String> objectNameList) {
        minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(minioProperties.getBucketName())
                .objects(objectNameList.stream().map(DeleteObject::new)
                        .collect(Collectors.toList()))
                .build());
    }

    /**
     * 拷贝文件
     *
     * @param bucketName     源桶名
     * @param objectName     源对象名称
     * @param destBucketName 目标桶名
     * @param destObjectName 目标对象名称
     * @return void
     * @date 2021/11/3 10:35
     */
    public void copyObject(String bucketName, String objectName, String destBucketName, String destObjectName) {
        try {
            minioClient.copyObject(CopyObjectArgs.builder().bucket(destBucketName)
                    .object(destObjectName)
                    .source(CopySource.builder()
                            .bucket(bucketName)
                            .object(objectName)
                            .build())
                    .build());
        } catch (Exception e) {
            log.error("Failed to copy object", e);
            throw new MinioBusinessException(HttpCode.INTERNAL_SERVER_ERROR, "Failed to copy object");
        }
    }

    /**
     * 获取文件流文件
     *
     * @param bucketName 桶名
     * @param objectName 对象名称
     * @return void
     * @date 2021/11/3 10:35
     */
    public InputStream getObject(String bucketName, String objectName) {
        try {
            return minioClient.getObject(GetObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .build());
        } catch (Exception e) {
            log.error("Failed to get the file stream file", e);
        }
        return null;
    }

    /**
     * 断点下载
     *
     * @param bucketName bucket名称
     * @param objectName 文件名称
     * @param offset     起始字节的位置
     * @param length     要读取的长度
     * @return 流
     * @date 2021/11/3 10:35
     */
    public InputStream getObject(String bucketName, String objectName, long offset, long length) {
        try {
            return minioClient.getObject(GetObjectArgs.builder().bucket(bucketName)
                    .object(objectName)
                    .offset(offset)
                    .length(length)
                    .build());
        } catch (Exception e) {
            log.error("Failed to breakpoint download object", e);
            throw new MinioBusinessException(HttpCode.INTERNAL_SERVER_ERROR, "Failed to breakpoint download object");
        }
    }

    /**
     * 下载文件
     *
     * @param bucketName 桶名
     * @param objectName 对象名称
     * @param fileName   下载存放路径
     * @return void
     * @date 2021/11/3 10:35
     */
    public void downloadObject(String bucketName, String objectName, String fileName) {
        try {
            minioClient.downloadObject(DownloadObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .filename(fileName)
                    .build());
        } catch (Exception e) {
            log.error("Failed to download object", e);
            throw new MinioBusinessException(HttpCode.INTERNAL_SERVER_ERROR, "Failed to download object");
        }
    }

    /**
     * 根据文件前置查询文件
     *
     * @param bucketName 桶名
     * @param prefix     对象前缀
     * @param recursive  是否递归查找，如果是false,就模拟文件夹结构查找
     * @return void
     * @date 2021/11/3 10:35
     */
    public List<Item> getAllObjectsByPrefix(String bucketName, String prefix, boolean recursive) {
        try {
            List<Item> list = Lists.newArrayList();
            Iterable<Result<Item>> iterable = minioClient.listObjects(ListObjectsArgs.builder()
                    .bucket(bucketName)
                    .prefix(prefix)
                    .recursive(recursive)
                    .build());
            if (iterable != null) {
                Assert.notNull(iterable.iterator(), "iterable result is null");
                for (Result<Item> itemResult : iterable) {
                    list.add(itemResult.get());
                }
            }
            return list;
        } catch (Exception e) {
            log.error("Failed to get all object", e);
            throw new MinioBusinessException(HttpCode.INTERNAL_SERVER_ERROR, "Failed to get all object");
        }
    }

    /**
     * 获取文件url
     *
     * @param bucketName 桶名
     * @param objectName 对象名称
     * @return void
     * @date 2021/11/3 10:35
     */
    public String getObjectUrl(String bucketName, String objectName) {
        try {
            return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .method(Method.GET)
                    .build());
        } catch (Exception e) {
            log.error("Failed to get object url", e);
            throw new MinioBusinessException(HttpCode.INTERNAL_SERVER_ERROR, "Failed to get object url");
        }
    }
}
